package viewbuilder.java;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class HtmlNode {

    String nodeName;
    List<HtmlAttribute> attributes = new ArrayList<HtmlAttribute>();
    List<HtmlNode> children = new ArrayList<HtmlNode>();

    String text;

    public String render() {
        StringBuffer html = new StringBuffer();
        addTo( html );
        return html.toString();
    }

    protected void addTo( StringBuffer sb ) {
        if ( text != null ) {
            sb.append( text );
        } else {
            sb.append( "\n<" )
                .append( nodeName );
            addAttributes( sb );
            sb.append( ">" );

            for ( HtmlNode node : children ) {
                node.addTo( sb );
            }

            sb.append( "\n</" )
                .append( nodeName )
                .append( ">" );
        }
    }

    private void addAttributes( StringBuffer sb ) {
        for ( HtmlAttribute attribute : attributes ) {
            sb.append( " " )
                .append( attribute.name )
                .append( "=\"" )
                .append( attribute.value )
                .append( "\"" );
        }
    }
}
